package written;

import java.util.concurrent.CountDownLatch;

/**
 * 2个线程交替打印100以内的奇偶数
 *
 * @author TANGYE
 * @date 2021-01-02 11:08
 **/
public class QuestionFour implements Runnable {

    private static int num = 1;
    private final static int MAX = 100;
    private static Object lock = new Object();
    private CountDownLatch cdl;

    public QuestionFour(CountDownLatch cdl) {
        this.cdl = cdl;
    }

    public static void printNum() throws InterruptedException {
        synchronized (lock) {
            lock.notify();
            System.out.println(Thread.currentThread().getName() + ": " + num);
            num++;
            if (num <= MAX) {
                lock.wait();
            }
        }
    }

    @Override
    public void run() {
        while (num <= MAX) {
            try {
                printNum();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        cdl.countDown();
    }

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch cdl = new CountDownLatch(2);
        Thread t1 = new Thread(new QuestionFour(cdl), "ThreadOne");
        Thread t2 = new Thread(new QuestionFour(cdl), "ThreadTwo");
        t1.start();
        t2.start();
        cdl.await();
    }
}
